package core.database;

import jade.util.Logger;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class StatementInsert {
	
	private Logger log = Logger.getJADELogger(this.getClass().getName());
	
	private Connection dbCon;
	private String tableName;
	private boolean first;

	private String strValues;
	private String strFields;
	private Statement st;
	
	public StatementInsert (Connection dbCon) {
		this.dbCon = dbCon;
		this.tableName=null;
		first=true;
		st= null;
	
	}
	
	
	public void addSetFieldValue ( String field, String value){
		if (first){
			strFields = field;
			strValues = value;
			first = false;
		} else {
			strFields = strFields + ","+field;
			strValues = strValues+ ",'" +value+"'";
		}
	}
	
	public void addSetFieldValue ( String field, Long value){
		if (first){
			strFields = field;
			strValues = "" + value;
			first = false;
		} else {
			strFields = strFields + ","+field;
			strValues = strValues+ "," +value;
		}
	}
	
	public void setTableName ( String tableName){
		this.tableName = tableName;
	}
	
	
	public void executeInsert() throws SQLException{
		if (tableName != null && strValues != null && strFields != null) {
			String query = "insert into "+tableName+" "+strFields + " VALUES ("+strValues+")";
			log.info("Execute query insert:" + query);
			st = dbCon.createStatement();
			st.execute(query);
		}

	}
	
	public void close() throws SQLException{
		
		if (st != null) st.close();
	}
	
	public long getSequenceValue( String sequence) throws SQLException{
		Statement stId = dbCon.createStatement();
		String query = "select " +sequence+".nextval from dual";
		ResultSet rs = stId.executeQuery(query);
		rs.next();
		long newId =  rs.getLong("NEXTVAL");
		stId.close();
		rs.close();
		return newId;
	}
	
	
}

